﻿using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.DataEntity.Metadata.Service;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.Core.MFG.EntityHelper;
using Kingdee.K3.FIN.Core;
using RK.BillPlugIn.Ronma;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.SerivesPlugin.Ronma
{
    [Description("润马：设置样品、废品仓进出单据的库存状态为不参与核算"), HotUpdate]
    public class SetStockStatusId : AbstractOperationServicePlugIn
    {
        //public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        //{
        //    base.BeforeExecuteOperationTransaction(e);
        //    var formId = this.BusinessInfo.GetForm().Id;
        //    //获取主业务组织
        //    OrgField orgField = this.BusinessInfo.MainOrgField;
        //    //组织-业务数据字典
        //    Dictionary<long, List<DynamicObject>> orgAndOrders = GetOrgAndOrders(orgField, e);
        //    var orgId=orgAndOrders.Keys.First();
        //    DetailEntity info = GetDetailInfo(formId);
        //    var obj = e.SelectedRows.Select(s => s.DataEntity).FirstOrDefault();
        //    DynamicObjectCollection rows = obj.GetDynamicValue<DynamicObjectCollection>(info.OrmId);
        //    for (int i = 0; i < rows.Count; i++)
        //    {
        //        var stock = rows[i][info.stockId] as DynamicObject;
        //        string stockName = stock["Name"].ToString();
        //        if (stockName.Contains("样品") || stockName.Contains("废品"))
        //        {
        //            (rows[i][info.FStockStatusId] as DynamicObject)["number"] = "KCZT001";
        //            //this.Model.SetItemValueByNumber("FStockStatusId", "KCZT001", i);
        //        }
        //    }
        //}

        private Dictionary<long, List<DynamicObject>> GetOrgAndOrders(OrgField orgField, BeforeExecuteOperationTransaction e)
        {
            Dictionary<long, List<DynamicObject>> orgAndOrders = new Dictionary<long, List<DynamicObject>>();
            //主业务组织不为空按组织分组
            if (orgField != null)
            {
                var b = e.SelectedRows.Select(s => s.DataEntity).ToList();
                var a = Convert.ToInt64((orgField.GetFieldValue(b.FirstOrDefault()) as DynamicObject)["id"]);
                orgAndOrders.Add(a, b);
                //orgAndOrders = e.DataEntitys.GroupBy(g => Convert.ToInt64((orgField.GetFieldValue(g) as DynamicObject)["id"])).ToDictionary(t => t.Key, t => t.ToList());
            }
            //取当前组织
            else
            {
                orgAndOrders.Add(this.Context.CurrentOrganizationInfo.ID, e.SelectedRows.Select(s => s.DataEntity).ToList());
            }
            return orgAndOrders;
        }

        public override void BeforeDoSaveExecute(BeforeDoSaveExecuteEventArgs e)
        {
            base.BeforeDoSaveExecute(e);
            var formId = this.BusinessInfo.GetForm().Id;
            //获取主业务组织
            //OrgField orgField = this.BusinessInfo.MainOrgField;
            //Dictionary<long, List<DynamicObject>> orgAndOrders = GetOrgOrders(orgField, e);
            //var orgId = orgAndOrders.Keys.First();
            DetailEntity info = GetDetailInfo(formId);
            var obj = e.DataEntities.FirstOrDefault();
            BaseDataField FStockStatusId = this.BusinessInfo.GetField("FStockStatusId") as BaseDataField;
            DynamicObjectCollection rows = obj.GetDynamicValue<DynamicObjectCollection>(info.OrmId);
            for (int i = 0; i < rows.Count; i++)
            {
                var stock = rows[i][info.stockId] as DynamicObject;
                string stockName = stock["Name"].ToString();
                if (stockName.Contains("样品") || stockName.Contains("废品"))
                {
                    var statusid = Api.ExecuteBillQuery(this.Context, "BD_StockStatus", "fstockstatusid", "fnumber='KCZT001'", "fstockstatusid", 1);
                    var obj2 = BusinessDataServiceHelper.LoadSingle(this.Context, statusid.FirstOrDefault().FirstOrDefault(), FStockStatusId.RefFormDynamicObjectType);
                    rows[i][info.StockStatusId_Id] = Convert.ToInt32(statusid.FirstOrDefault().FirstOrDefault());
                    rows[i][info.FStockStatusId] = obj2;
                    //(rows[i][info.FStockStatusId] as DynamicObject)["number"] = "KCZT001";
                    //this.Model.SetItemValueByNumber("FStockStatusId", "KCZT001", i);
                }
            }
        }

        private Dictionary<long, List<DynamicObject>> GetOrgOrders(OrgField orgField, BeforeDoSaveExecuteEventArgs e)
        {
            Dictionary<long, List<DynamicObject>> orgAndOrders = new Dictionary<long, List<DynamicObject>>();
            //主业务组织不为空按组织分组
            if (orgField != null)
            {
                orgAndOrders = e.DataEntities.GroupBy(g => Convert.ToInt64((orgField.GetFieldValue(g) as DynamicObject)["id"]))
                    .ToDictionary(t => t.Key, t => t.ToList());
            }
            //取当前组织
            else
            {
                orgAndOrders.Add(this.Context.CurrentOrganizationInfo.ID, e.DataEntities.ToList());
            }
            return orgAndOrders;
        }

        private DetailEntity GetDetailInfo(string formId)
        {
            DetailEntity detail = new DetailEntity();
            detail.stockId = "StockId";
            detail.FStockStatusId = "StockStatusId";
            detail.StockStatusId_Id = "StockStatusId_Id";
            switch (formId)
            {
                //采购入库单
                case "STK_InStock":
                    detail.OrmId = "InStockEntry";
                    detail.FStockStatusId = "StockStatusId";
                    break;
                //采购退料单
                case "PUR_MRB":
                    detail.OrmId = "PUR_MRBENTRY";
                    detail.FStockStatusId = "StockStatusId";
                    break;
                //其他入库单
                case "STK_MISCELLANEOUS":
                    detail.OrmId = "STK_MISCELLANEOUSENTRY";
                    detail.stockId = "FSTOCKID";
                    detail.FStockStatusId = "STOCKSTATUSID";
                    break;
                //其他出库单
                case "STK_MisDelivery":
                    detail.OrmId = "BillEntry";
                    detail.FStockStatusId = "StockStatusId";
                    break;
                //受托加工材料入库单
                case "STK_OEMInStock":
                    detail.OrmId = "OEMInStockEntry";
                    detail.FStockStatusId = "StockStatusId";
                    break;
                //受托加工材料退料单
                case "STK_OEMInStockRETURN":
                    detail.OrmId = "OEMInStockRTNEntry";
                    detail.FStockStatusId = "StockStatusId";
                    break;
                //销售出库单
                case "SAL_OUTSTOCK":
                    detail.OrmId = "SAL_OUTSTOCKENTRY";
                    break;
                //销售退货单
                case "SAL_RETURNSTOCK":
                    detail.OrmId = "SAL_RETURNSTOCKENTRY";
                    break;
                //简单生产领料单
                case "SP_PickMtrl":
                    detail.OrmId = "Entity";
                    break;
                //简单生产退料单
                case "SP_ReturnMtrl":
                    detail.OrmId = "Entity";
                    break;
                //生产补料单
                case "PRD_FeedMtrl":
                    detail.OrmId = "Entity";
                    break;
                //生产领料单
                case "PRD_PickMtrl":
                    detail.OrmId = "Entity";
                    break;
                //生产退料单
                case "PRD_ReturnMtrl":
                    detail.OrmId = "Entity";
                    break;
                default:
                    detail.OrmId = "Entity";
                    detail.stockId = "StockId";
                    break;
            }
            return detail;
        }
    }
}
